package com.gjxx.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
 * 多线程注入方法,工具类
 * @Author  my.guo
 */
@Configuration
public class SpringBeanUtil implements ApplicationContextAware {
    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtil.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    /**
     * 通过name获取 Bean.
     * @return
     */
    public static Object getBean(String name) {
        if (applicationContext == null){
            throw new RuntimeException("applicationContext注入失败");
        }
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     * @return
     */
    public static <T> T getBean(Class<T> type) {
        if (applicationContext == null){
            throw new RuntimeException("applicationContext注入失败");
        }
        return getApplicationContext().getBean(type);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     * @return
     */
    public static <T> T getBean(String name, Class<T> type) {
        if (applicationContext == null){
            throw new RuntimeException("applicationContext注入失败");
        }
        return getApplicationContext().getBean(name, type);
    }
}

